<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

include 'MSWebGUI/FileList.php';
include 'Classes/FileList.php';

function DeleteEvent($database )
{
		$table = new DBTable($database,$_POST['DBTableName']);
//		$tableStructure = $table->getTableStructure();
//		$keys = array_keys($tableStructure);

		$timeNow = new DateTime("now");
//		$sql = "UPDATE ".$_POST['DBTableName']." SET DeletedWhen = '".$timeNow->format("Y-m-d H:i")."', DeletedBy = '".$_POST['UserID']."' ";
		$sql = "UPDATE ".$_POST['DBTableName']." SET  ";
		$sql .= " WHERE ".$table->getPrimaryKey()."=".$_POST['RecordID'];

//		echo $sql;

		$database->ExecuteSQL($sql);
}

function InsertIntoTable($database,$tablename,$array,$ParentTableID)
{
//	echo "Going to insert into $tablename<br>";
//	print_r($array);
//	echo "<br>";
//	echo $ParentTableID."<br>";
	// Need to get a new ID if it is parent Table
	// Need to insert this ID if not - compare $tablename with $_POST['DBTableName'] to decide
	
 	$isParentTable = ($tablename==$_POST['DBTableName']);

	$table = new DBTable($database,$tablename);
	$tableStructure = $table->getTableStructure();
//	print_r($tableStructure);
	
	$repeatWeeks = 0;
	if(isset($_POST['RepeatWeeks']))$repeatWeeks = $_POST['RepeatWeeks'];
	for($i=0;$i <= $repeatWeeks;$i++)
	{
		
		$sql = "INSERT INTO ".$tablename." (";
//		$sql.= "CreatedWhen,CreatedBy,";

		$includeSQL = false;
		foreach($array as $key => $value)
		{
//			echo $key."<br>";
			if(isset($tableStructure[$key]))
				if($tableStructure[$key]=="enum('multienum')")continue;
			
			if($key=='FSFileName'); // ignore
			elseif($key=='FSFileSize'); // ignore
			elseif($key=='FSFileType'); // ignore
//			elseif($key=='FSFileContents'); // ignore
			elseif(isset($tableStructure[$key]))
			{
//				echo $tableStructure[$key]."<br>";
				if($tableStructure[$key]=="enum('multienum')");
				else 
				{
					$sql .= $key.",";
					$includeSQL=true; // only run the sql if there is a field to add
				}
			}
			elseif($key=='MAXFILESIZE')
			{
				$sql .= "FSFileName,";
				$sql .= "FSFileSize,";
				$sql .= "FSFileType,";
//				$sql .= "BLOBFileContents,";
				$includeSQL=true;
			}
		}
		if(!$isParentTable)$sql .= substr($_POST['DBTableName'],0,-1)."IDP,";
		$sql = substr($sql,0,strlen($sql)-1).") VALUES (";
//		$datetime = new DateTime("now");
//		$sql.= "'".$datetime->format("Y-m-d H:i")."',".$_POST['UserID'].",";
		foreach($array as $key => $value)
		{
			if(isset($tableStructure[$key]))
				if($tableStructure[$key]=="enum('multienum')")continue;
			
			if($key=='FSFileName'); // ignore
			elseif($key=='FSFileSize'); // ignore
			elseif($key=='FSFileType'); // ignore
//			elseif($key=='FSFileContents'); // ignore
			elseif(isset($tableStructure[$key]))
			{
				$sql .= "'".addslashes($value)."',";
			}
			elseif($key=='MAXFILESIZE')
			{
//				print_r($_FILES);
				$Filename =     $_FILES['InsertRecord_Files_FSFileSize']['name'];
				$localname = $_FILES['InsertRecord_Files_FSFileSize']['tmp_name'];
				$Filetype = $_FILES['InsertRecord_Files_FSFileSize']['type'];
				
				
				$fp      = fopen($localname, 'r');
				$Filesize = filesize($localname);
//				$Filecontents = fread($fp, $Filesize);
//				$Filecontents = addslashes($Filecontents);
//				echo $Filecontents;
				fclose($fp);
				
				$NewName = "ResourceFiles/Files_FSFile_".$ParentTableID;
//				if(move_uploaded_file($localname,$NewName)==true)echo "Success<br>";		
				move_uploaded_file($localname,$NewName);		
				
				$sql .= "'".addslashes($Filename)."',";
				$sql .= "'".addslashes($Filesize)."',";
				$sql .= "'".addslashes($Filetype)."',";
//				$sql .= "'".$Filecontents."',";
			}
		}
		if(!$isParentTable)$sql .= $ParentTableID.",";
		$sql = substr($sql,0,strlen($sql)-1).")";

		$parentTableID = -1;
//		echo $sql."includeSQL = ".$includeSQL."<br>";
		if($includeSQL)
		{
			$database->ExecuteSQL($sql);
//			echo $sql.mysql_error()."<br>";
//			echo mysql_insert_id()."<br>";
			$EventID = mysql_insert_id();
			$parentTableID = $EventID;
		}
		// are there any special fields (eg multienumerations)

		foreach($array as $key => $value)
		{
//			echo $key."<br>";
			if(isset($tableStructure[$key]))
			{
//				echo $tableStructure[$key]."<br>";
				if($tableStructure[$key]=="enum('multienum')")
					{
//					print_r ($_POST["InsertRecord_".$tablename."_".$key]);
//					echo "<br>";
//					echo "Tablename = ".$tablename."<br>";
					if(isset($_POST["InsertRecord_".$tablename."_".$key]))
						{
						foreach($_POST["InsertRecord_".$tablename."_".$key] as $value)
							{
							$sql = "INSERT INTO ".$key."s (".substr($tablename,0,-1)."ID,".$key."NameID) VALUES (".$ParentTableID.",".$value.")";
//							print $sql."<br>";
							$database->ExecuteSQL($sql);
//							echo $sql.mysql_error()."<br>";
//							echo mysql_insert_id()."<br>";
							
							}
						}
					}
			}
		}

//		echo $keyValues['Start'];
		if(isset($keyValues['Start']))
		{
			$time = new DateTime($keyValues['Start']);
			date_modify($time,"+7 day");
			$keyValues['Start']=$time->format("Y-m-d H:i");
		}

//		echo $keyValues['End'];
		if(isset($keyValues['End']))
		{
			$time = new DateTime($keyValues['End']);
			date_modify($time,"+7 day");
			$keyValues['End']=$time->format("Y-m-d H:i");
		}

//		echo ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");

//		($keyValues['Start']) = ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");
//		($keyValues['End']) = ((new DateTime($keyValues['End']))->modify("+7 day"))->format("Y-m-d H:i");
//		$keyValues['End']->modify("+7 day");
	return($parentTableID);
	}
}

function InsertEvent($Database)
{
	$FieldArray;
	$InsertID=-1;
	$ParentTableID=-1;
	$Table = "";
	foreach($_POST as $key => $value)
	{
//		echo $key."<br>";
		$parts = explode('_',$key,3);
		if($parts[0]=="InsertRecord")
		{
			if($parts[1]!=$Table)
			{
				if($Table!="")$InsertID=InsertIntoTable($Database,$Table,$FieldArray,$ParentTableID);
//				echo "Insert ID = ".$InsertID."<br>";
				if($ParentTableID==-1)$ParentTableID=$InsertID;
				$FieldArray=array();
				$Table = $parts[1];
			}
//			print $value."<br>";
			$FieldArray[$parts[2]] = $value;
		}
	}
//	print_r($FieldArray);
	if($Table!="")$InsertID=InsertIntoTable($Database,$Table,$FieldArray,$ParentTableID);
	if($ParentTableID==-1)$ParentTableID=$InsertID;
	
	// update submit action
	$date = new DateTime();
	$sql = "INSERT INTO Actions (ResourceID, ActionTypeID, ActionDate, UserID)
	VALUES ('".$ParentTableID."','1','".$date->format('Y-m-d H:i:s')."','".$_POST['UserID']."')";
//	echo $sql."<br>";
	$Database->ExecuteSQL($sql);
	
	// update status
	$sql = "INSERT INTO ResourceStatuss (ResourceID, StatusID, Date)
	VALUES ('".$ParentTableID."','2','".$date->format('Y-m-d H:i:s')."')";
//	echo $sql."<br>";
	$Database->ExecuteSQL($sql);
	
	
		

/********************************************************/

/******************************************************************/


}

function UpdateEvent($database )
{
	DeleteEvent($database );
	InsertEvent($database );
}


$Action = "";
if(isset($_POST))
{
	if (isset($_POST['Action']))
	{
		$Action = $_POST['Action'];
	}
}

//$database = new Database("localhost","mstoddart_CMR","CMRUser","cathedralmusic");
//$database = new Database("localhost","mstoddart_CMRTest","CMRTestUser2","cathedralmusic");
$xml = simplexml_load_file('config/config.xml');

$databaseXML = $xml->Database;

$database = new Database($databaseXML->Server,$databaseXML->Database,$databaseXML->Username,$databaseXML->Password);


//echo "Action=".$Action."<br>";;
switch($Action)
{
/*
	case 'members':
//		$thisPage->setContentHTML("http://www.stnicholascathedralmusic.co.uk/PageMembers.php");
		$thisPage->setContentClass("PanelMembers");
		$thisPage->setRightImage1("../../../../sncm/Images/pilgrimwalk.jpg");
		$thisPage->setHeaderImage("../../../../sncm/Images/run.jpg");
		$theAuthenticator = new SNCMAuthenticator();
		$theAuthenticator->setDatabase($database);
		$theAuthenticator->setUserTable("MemberUsers");
		$thisPage->setAuthenticator($theAuthenticator);
		break;
*/
		case 'logoff':
	
			$sql="UPDATE UserSessions SET Expires = '2010-01-01 01:00:00' WHERE SessionID = '".$_POST['SessionID']."' AND Username = '".$_POST['User'];
//			echo $sql;
			$database->ExecuteSql($sql);
			$thisPage = new CMRPage();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			//		$thisPage->setHeaderImage("../../../../sncm/Images/sage.jpg");
			break;
					
		case 'resources':
			$thisPage = new CMRPageResources();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
		case 'ViewRecord':
			$thisPage = new CMRPageResources();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
		case 'submit':
			$thisPage = new CMRPageSubmit();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
			case 'InsertRecord':
			InsertEvent($database );
			$thisPage = new CMRPage();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
		case 'approve':
			$thisPage = new CMRPageApprove();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
		case 'ViewFile':
			$thisPage = new CMRPageResources();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
			
			case 'home':
		default:
			
			$thisPage = new CMRPage();
			$thisPage->setRightImage1("Images/ACathedral.gif");
			$thisPage->setRightColumnWidth("100");
			break;
}	
				
$theAuthenticator = new CMRAuthenticator();
$theAuthenticator->setDatabase($database);
$theAuthenticator->setUserTable("Users");
$thisPage->setAuthenticator($theAuthenticator);

$thisPage->setDatabase($database);


echo $thisPage->getHTML();
	
?>